package com.example.yichuangyun.ui.activity.follow;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityFollowListBinding;
import com.example.yichuangyun.dialog.TimePicker;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.business.FollowDataModel;
import com.example.yichuangyun.model.business.LabelModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.ui.adapter.FollowAdapter;
import com.example.yichuangyun.ui.adapter.LabelAdapter2;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class FollowListActivity extends BaseActivity<ActivityFollowListBinding, BaseViewModel> implements LabelAdapter2.OnLabelItemListener {

    private List<FollowDataModel.FollowRecordModel> followData = new ArrayList<>();
    private FollowAdapter adapter;
    private int page = 1;
    private boolean isDesc = true;
    private List<LabelModel> followTypeLabelData = new ArrayList<>();
    private LabelAdapter2 followTypeAdapter, followClassifyAdapter;
    private TimePicker timePicker;
    private int flag;
    private String findType;
    /**
     * 1通讯录，2商机，null全部
     */
    private String followClassify;

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        binding.includeTop.llBack.setVisibility(View.VISIBLE);
        binding.includeTop.tvTitleText.setText(getString(R.string.follow));
        binding.includeTop.tvBusinessCount.setVisibility(View.INVISIBLE);
        binding.includeTop.ivAddBusiness.setVisibility(View.GONE);
        binding.includeSelect.recyclerViewFollowType.setLayoutManager(new GridLayoutManager(context, 3, LinearLayoutManager.VERTICAL, false));
        binding.includeSelect.recyclerViewFollowClassify.setLayoutManager(new GridLayoutManager(context, 3, LinearLayoutManager.VERTICAL, false));
        List<LabelModel> followClassifyLabelData = new ArrayList<>();
        followClassifyLabelData.add(new LabelModel(getString(R.string.all), true));
        followClassifyLabelData.add(new LabelModel(getString(R.string.address_book), "1", false));
        followClassifyLabelData.add(new LabelModel(getString(R.string.business), "2", false));
        followClassifyAdapter = new LabelAdapter2(1, context, followClassifyLabelData, this);
        binding.includeSelect.recyclerViewFollowClassify.setAdapter(followClassifyAdapter);
        initTimePicker();
        getFollowType();
        getFollowRecord(page);
    }

    /**
     * 跟进方式
     */
    private void getFollowType() {
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getLabel(Constant.followType), new MyObserver<HttpRespond<List<LabelModel>>>() {
            @Override
            protected void onSuccess(HttpRespond<List<LabelModel>> listHttpRespond) {
                if (Constant.SUCCESS == listHttpRespond.code) {
                    if (listHttpRespond.data != null && listHttpRespond.data.size() > 0) {
                        List<LabelModel> list = new ArrayList<>();
                        for (LabelModel labelModel : listHttpRespond.data) {
                            if (!labelModel.getRemark().contains("400") && !labelModel.getRemark().equals(getString(R.string.business_group))) {
                                list.add(labelModel);
                            }
                        }
                        followTypeLabelData = list;
                        followTypeLabelData.add(new LabelModel(getString(R.string.all), false));
                        followTypeAdapter.onRefresh(followTypeLabelData);
                    }
                }
            }
        });
    }

    /**
     * 跟进记录
     */
    private void getFollowRecord(int page) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("followsType", followClassify); // 跟进类型 1.通讯录跟进, 2.商机跟进, null全部
            jsonObject.put("findType", findType);
            jsonObject.put("startFollowTime", binding.includeSelect.tvStartTime.getText().toString());
            jsonObject.put("endFollowTime", binding.includeSelect.tvEndTime.getText().toString());
            jsonObject.put("startNextFollowTime", binding.includeSelect.tvStartNextTime.getText().toString());
            jsonObject.put("endNextFollowTime", binding.includeSelect.tvEndNextTime.getText().toString());
            jsonObject.put("isSync", 1);
            jsonObject.put("order", isDesc ? "desc" : "asc");
            jsonObject.put("page", page);
            jsonObject.put("pageSize", Constant.pageSize);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getTabFollowLog(requestBody), new MyObserver<HttpRespond<FollowDataModel>>() {
            @Override
            protected void onSuccess(HttpRespond<FollowDataModel> followDataModelHttpRespond) {
                if (Constant.SUCCESS == followDataModelHttpRespond.code) {
                    if (followDataModelHttpRespond.data != null) {
                        if (followDataModelHttpRespond.data.getRecords() != null) {
                            List<FollowDataModel.FollowRecordModel> list = followDataModelHttpRespond.data.getRecords();
                            if (list.size() == 0) {
                                binding.smartRefreshLayout.finishLoadMoreWithNoMoreData();
                            }
                            if (page == 1) {
                                followData = list;
                                adapter.onRefresh(list);
                                binding.smartRefreshLayout.finishRefresh();
                            } else {
                                adapter.addData(list);
                                binding.smartRefreshLayout.finishLoadMore();
                            }
                        }
                    }
                } else {
                    binding.smartRefreshLayout.finishRefresh();
                    binding.smartRefreshLayout.finishLoadMore();
                }
                dismissLoadingDialog();
            }

            @Override
            protected void onFail(Throwable e) {
                super.onFail(e);
                binding.smartRefreshLayout.finishRefresh();
                binding.smartRefreshLayout.finishLoadMore();
                dismissLoadingDialog();
            }
        });
    }

    @Override
    public void initCtrl() {
        adapter = new FollowAdapter(context, followData, 0);
        binding.recyclerView.setAdapter(adapter);
        followTypeAdapter = new LabelAdapter2(2, context, followTypeLabelData, this);
        binding.includeSelect.recyclerViewFollowType.setAdapter(followTypeAdapter);
    }

    @Override
    protected void initClick() {
        // 排序
        binding.includeTop.ivSort.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                showLoadingDialog();
                isDesc = !isDesc;
                page = 1;
                getFollowRecord(page);
            }
        });

        // 筛选
        binding.includeTop.ivSelect.setOnClickListener(v -> binding.drawerLayout.openDrawer(GravityCompat.END));
        binding.includeSelect.tvStartTime.setOnClickListener(v -> {
            flag = 1;
            timePicker.showPickerView();
        });
        binding.includeSelect.tvEndTime.setOnClickListener(v -> {
            flag = 2;
            timePicker.showPickerView();
        });
        binding.includeSelect.tvStartNextTime.setOnClickListener(v -> {
            flag = 3;
            timePicker.showPickerView();
        });
        binding.includeSelect.tvEndNextTime.setOnClickListener(v -> {
            flag = 4;
            timePicker.showPickerView();
        });
        binding.includeSelect.tvReset.setOnClickListener(v -> {
            findType = null;
            followClassify = null;
            binding.includeSelect.tvStartTime.setText("");
            binding.includeSelect.tvEndTime.setText("");
            binding.includeSelect.tvStartNextTime.setText("");
            binding.includeSelect.tvEndNextTime.setText("");
            followTypeAdapter.resetData();
            followClassifyAdapter.resetData2();
        });
        binding.includeSelect.tvConfirm.setOnClickListener(v -> {
            binding.drawerLayout.closeDrawers();
            page = 1;
            binding.recyclerView.scrollToPosition(0);
            binding.smartRefreshLayout.autoRefresh();
        });

        // 搜索
        binding.includeTop.ivSearch.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                JumpIntent.jump(this, SearchFollowActivity.class);
            }
        });

        binding.includeTop.llBack.setOnClickListener(v -> finish());

        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getFollowRecord(page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getFollowRecord(page);
            }
        });
    }

    private void initTimePicker() {
        timePicker = new TimePicker(this) {
            @Override
            public void confirm(String date) {
                if (flag == 1) {
                    binding.includeSelect.tvStartTime.setText(date);
                } else if (flag == 2) {
                    binding.includeSelect.tvEndTime.setText(date);
                } else if (flag == 3) {
                    binding.includeSelect.tvStartNextTime.setText(date);
                } else {
                    binding.includeSelect.tvEndNextTime.setText(date);
                }
            }
        };
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onLabelItemClickListener(int flag, LabelModel model) {
        if (flag == 1) {
            followClassify = model.isSelect() ? model.getCode() : null;
        } else {
            findType = model.isSelect() ? model.getCode() : null;
        }
    }
}